<template>
    <Modal v-model:visible="isShowModal" title="重置密码" @ok="handleOk" @cancel="handleCancel" ok-text="提交"
        cancel-text="取消" :loading="loading">
        <Form :model="formState" ref="formRef" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" :rules="rules">
            <FormItem label="新密码" name="newPassword">
                <InputPassword v-model:value="formState.newPassword" placeholder="请输入密码" allowClear></InputPassword>
            </FormItem>
        </Form>
    </Modal>
</template>

<script lang="ts" setup>
import { Modal, Form, Input, message } from 'ant-design-vue'
import { Rule } from 'ant-design-vue/es/form';
import { CompanyUserApi, CompanyUserResetPasswordRequest } from '@/api';

const FormItem = Form.Item;
const InputPassword = Input.Password;

const emit = defineEmits(['ok']);

const isShowModal = ref(false)
const loading = ref(false)
const userId = ref<string>();
const formState = reactive<CompanyUserResetPasswordRequest>({
    newPassword: ''
})
const formRef = ref()
const rules: Record<string, Rule[]> = {
    newPassword: [{ required: true, message: "请输入新密码", trigger: 'blur' }],
};
const handleOpen = (id: string) => {
    userId.value = id;
    isShowModal.value = true;
}

const handleOk = () => {
    loading.value = true;
    formRef.value
        .validate()
        .then(async () => {
            if (userId.value && formState.newPassword) {
                await CompanyUserApi.companyuserResetpassword(userId.value, { newPassword: formState.newPassword })
                message.success('重置成功')
                isShowModal.value = false; // 关闭弹窗
            }
        })
        .catch((err: any) => {
            console.log('校验失败', err);
        }).finally(() => {
            loading.value = false;
        });
}

const handleCancel = () => {
    userId.value = undefined;
    formState.newPassword = ''
    isShowModal.value = false;
}

defineExpose({ handleOpen })
</script>